﻿/******************************************************   
创建者: ljj
创建时间: 2018-01-04
修改:
修改时间: 
功能: 小类_细项设置项
 ******************************************************/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm;
using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.library;
using com.nm.library.Helper;
using george.Data;
using george.Helper;
using NHibernateVertica;
using InventoryToPredictAPI.model;
using VerticaAPI;

namespace InventoryToPredictAPI
{
    [Description("小类_细项设置项")]
    public class DwDetailsPercentageSettingHandler : BaseHandler
    {
        public VerticaDataHelper Helper { get; set; } = new VerticaDataHelper();

        /// Writer：ljj
        /// Create Date：2018-01-04
        [MustLogin]
        [Description("小类_细项设置项")]
        [ReturnType(typeof(PaperData<DwDetailsPercentageSettingModel.ShowModel>))]
        public ApiResult GetDwDetailsPercentageSettingList([ParamDescription("年份")] string Year,
            [ParamDescription("周")] string Week = "", [ParamDescription("大类")] string Category = "",
            [ParamDescription("性别")] string Gender = "", [ParamDescription("页码")] int Page = 1,
            [ParamDescription("页数")] int Size = 10)
        {
            try
            {
                var companyID = UserInfo.UserCompanyId;
                var extrSource = UserInfo.UserExtrSource;
                if (string.IsNullOrEmpty(companyID))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(extrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                if (string.IsNullOrEmpty(Year))
                {
                    return Error("请选择年份!");
                }
                var con = "AND Week != 0";
                if (Year == "-1")
                {
                    Year = DateTime.Now.Year.ToString();
                    con = "";
                    Week = "0";
                }
                var categoryStr = Category.GetString();
                var count = ReturnDwDetailsPercentageSettingCount(extrSource, companyID, Year, Week, categoryStr, Gender, con);
                var result = PaperData<DwDetailsPercentageSettingModel.ShowModel>.Create(count, Size, Page);
                var group = ReturnDwDetailsPercentageSettingList(extrSource, companyID, Year, Week, categoryStr, Gender,
                    Page, Size, con).GroupBy(d => new
                {
                    d.Year,
                    d.Week,
                    d.Category,
                    d.Gender,
                    d.KindName,
                    d.SexName,
                });
                var list = group.Select(d => new DwDetailsPercentageSettingModel.ShowModel
                {
                    Year = d.Key.Year,
                    Week = d.Key.Week,
                    Category = d.Key.Category,
                    Gender = d.Key.Gender,
                    KindName = d.Key.KindName,
                    SexName = d.Key.SexName,
                    list = d.Select(r => new DwDetailsPercentageSettingModel.ListModel
                    {
                        Detail = r.Detail,
                        Persentage = r.Persentage,
                        IsHome = r.IsHome,
                    }).OrderBy(r => r.Detail).ToList(),
                }).OrderBy(d => d.Year).ThenBy(d => d.Week).ThenBy(d => d.Category).ThenBy(d => d.Gender).ToList();
                result.Items = list;
                return Success(result);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error("获取数据失败!");
            }
        }

        /// <summary>
        /// 返回小类_细项设置项
        /// </summary>
        /// <param name="ExtrSource"></param>
        /// <param name="CompanyID"></param>
        /// <param name="Year"></param>
        /// <param name="Week"></param>
        /// <param name="Category"></param>
        /// <param name="Gender"></param>
        /// <param name="Page"></param>
        /// <param name="Size"></param>
        /// <returns></returns>
        /// Writer：ljj
        /// Create Date：2018-01-04
        public IList<DwDetailsPercentageSettingModel.SelectModel> ReturnDwDetailsPercentageSettingList(
            string ExtrSource, string CompanyID, string Year, string Week, string Category, string Gender, int Page,
            int Size, string Con)
        {
            try
            {
                var sql = $@"
SELECT  table2.* ,
        setting.IsHome ,
        setting.Detail ,
        setting.Persentage 
FROM    ( SELECT    *
          FROM      ( SELECT    setting.Extrsource ,
                                setting.CompanyId ,
                                setting.Year ,
                                setting.Week ,
                                setting.Category ,
                                setting.Gender ,
                                kind.KindName ,
                                sex.SexName ,
                                ROW_NUMBER() OVER ( ORDER BY setting.Extrsource, setting.CompanyId, setting.Year, setting.Week, setting.Category, setting.Gender ) AS Row
                      FROM      ( SELECT    *
                                  FROM      ndw.ndw_details_percentage_setting
                                  WHERE     ExtrSource = '{ExtrSource}'
                                            AND CompanyID = '{CompanyID}'
                                            AND Year = {Year}
                                            {Con}
                                            {(string.IsNullOrEmpty(Week) ? "" : $"AND Week = {Week}")}
                                            {(string.IsNullOrEmpty(Category) ? "" : $"AND Category in {Category}")}
                                            {(string.IsNullOrEmpty(Gender) ? "" : $"AND Gender = '{Gender}'")}
                                ) setting
                                INNER JOIN ( SELECT *
                                             FROM   nods.nods_erp_SD_Mat_Kind
                                             WHERE  ExtrSource = '{ExtrSource}'
                                                    {
                        (string.IsNullOrEmpty(Category) ? "" : $"AND KindID in {Category}")
                    }
                                           ) kind ON setting.Category = kind.KindID
                                                     AND setting.Extrsource = kind.ExtrSource
                                INNER JOIN ( SELECT *
                                             FROM   nods.nods_erp_SD_Mat_Sex
                                             WHERE  ExtrSource = '{ExtrSource}'
                                                    {(string.IsNullOrEmpty(Gender) ? "" : $"AND SexID = '{Gender}'")}
                                           ) sex ON setting.Gender = sex.SexID
                                                    AND setting.Extrsource = sex.ExtrSource
                      GROUP BY  setting.Extrsource ,
                                setting.CompanyId ,
                                setting.Year ,
                                setting.Week ,
                                setting.Category ,
                                setting.Gender ,
                                kind.KindName ,
                                sex.SexName
                    ) table1
          WHERE     Row BETWEEN ( {Page} - 1 ) * {Size} + 1 AND {Page}
                    * {Size}
        ) table2
        LEFT JOIN ( SELECT  *
                    FROM    ndw.ndw_details_percentage_setting
                    WHERE   ExtrSource = '{ExtrSource}'
                            AND CompanyID = '{CompanyID}'
                            AND Year = {Year}
                            {Con}
                            {(string.IsNullOrEmpty(Week) ? "" : $"AND Week = {Week}")}
                            {(string.IsNullOrEmpty(Category) ? "" : $"AND Category in {Category}")}
                            {(string.IsNullOrEmpty(Gender) ? "" : $"AND Gender = '{Gender}'")}
                  ) setting ON table2.Extrsource = setting.Extrsource
                               AND table2.CompanyId = setting.CompanyId
                               AND table2.Year = setting.Year
                               AND table2.Week = setting.Week
                               AND table2.Category = setting.Category
                               AND table2.Gender = setting.Gender";
                var cmd = Helper.GetSqlStringCommand(sql);
                var dt = Helper.ExecuteDataTable(cmd);
                var list = ModelConvertHelper<DwDetailsPercentageSettingModel.SelectModel>.ConvertToModel(dt);
                return list;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        /// <summary>
        /// 返回小类_细项设置项条数
        /// </summary>
        /// <param name="ExtrSource"></param>
        /// <param name="CompanyID"></param>
        /// <param name="Year"></param>
        /// <param name="Week"></param>
        /// <param name="Category"></param>
        /// <param name="Gender"></param>
        /// <param name="Page"></param>
        /// <param name="Size"></param>
        /// <returns></returns>
        /// Writer：ljj
        /// Create Date：2018-01-04
        public int ReturnDwDetailsPercentageSettingCount(string ExtrSource, string CompanyID, string Year, string Week,
            string Category, string Gender, string Con)
        {
            try
            {
                var sql = $@"SELECT    Count(1)
          FROM      ( SELECT    setting.Extrsource ,
                                setting.CompanyId ,
                                setting.Year ,
                                setting.Week ,
                                setting.Category ,
                                setting.Gender ,
                                kind.KindName ,
                                sex.SexName ,
                                ROW_NUMBER() OVER ( ORDER BY setting.Extrsource, setting.CompanyId, setting.Year, setting.Week, setting.Category, setting.Gender ) AS Row
                      FROM      ( SELECT    *
                                  FROM      ndw.ndw_details_percentage_setting
                                  WHERE     ExtrSource = '{ExtrSource}'
                                            AND CompanyID = '{CompanyID}'
                                            AND Year = {Year}
                                            {Con}
                                            {(string.IsNullOrEmpty(Week) ? "" : $"AND Week = {Week}")}
                                            {(string.IsNullOrEmpty(Category) ? "" : $"AND Category in {Category}")}
                                            {(string.IsNullOrEmpty(Gender) ? "" : $"AND Gender = '{Gender}'")}
                                ) setting
                                INNER JOIN ( SELECT *
                                             FROM   nods.nods_erp_SD_Mat_Kind
                                             WHERE  ExtrSource = '{ExtrSource}'
                                                    {
                        (string.IsNullOrEmpty(Category) ? "" : $"AND KindID in {Category}")
                    }
                                           ) kind ON setting.Category = kind.KindID
                                                     AND setting.Extrsource = kind.ExtrSource
                                INNER JOIN ( SELECT *
                                             FROM   nods.nods_erp_SD_Mat_Sex
                                             WHERE  ExtrSource = '{ExtrSource}'
                                                    {(string.IsNullOrEmpty(Gender) ? "" : $"AND SexID = '{Gender}'")}
                                           ) sex ON setting.Gender = sex.SexID
                                                    AND setting.Extrsource = sex.ExtrSource
                      GROUP BY  setting.Extrsource ,
                                setting.CompanyId ,
                                setting.Year ,
                                setting.Week ,
                                setting.Category ,
                                setting.Gender ,
                                kind.KindName ,
                                sex.SexName
                    ) table1";
                var cmd = Helper.GetSqlStringCommand(sql);
                var count = Convert.ToInt32(Helper.ExecuteScalar(cmd));
                return count;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        /// Writer：ljj
        /// Create Date：2018-01-04
        [MustLogin]
        [Description("历史周占比列表")]
        [ReturnType(typeof(IList<DwDetailsPercentageSettingModel.TitleModel>))]
        public ApiResult GetLeftTitle([ParamDescription("关键字")] string Keys = "")
        {
            try
            {
                var companyID = UserInfo.UserCompanyId;
                var extrSource = UserInfo.UserExtrSource;
                if (string.IsNullOrEmpty(companyID))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(extrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                if (!string.IsNullOrEmpty(Keys)&&!int.TryParse(Keys, out int y))
                {
                    return Error("请输入数字!");
                }
                var sql = $@"SELECT  Year AS YearV ,
        Week AS Weekv
FROM    ndw.ndw_details_percentage_setting
WHERE   Extrsource = '{extrSource}'
        AND CompanyId = '{companyID}'
GROUP BY Year ,
        Week
ORDER BY Year ,
        Week";
                var cmd = Helper.GetSqlStringCommand(sql);
                var dt = Helper.ExecuteDataTable(cmd);
                var list = ModelConvertHelper<DwDetailsPercentageSettingModel.TitleModel>.ConvertToModel(dt);
                for (var i = list.Count - 1; i >= 0; i--)
                {
                    if (list[i].YearV == DateTime.Now.Year &&
                        list[i].Weekv == CalendarHandler.GetWeekOfYear(DateTime.Now))
                    {
                        list.RemoveAt(i);
                    }
                }
                return Success(list.ToList());
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error("获取数据失败!");
            }
        }

        /// Writer：ljj
        /// Create Date：2018-01-04
        [MustLogin]
        [Description("应用周列表")]
        [ReturnType(typeof(IList<IGrouping<long, DwDetailsPercentageSettingModel.TitleModel>>))]
        public ApiResult GetRightDate()
        {
            try
            {
                var companyID = UserInfo.UserCompanyId;
                var extrSource = UserInfo.UserExtrSource;
                if (string.IsNullOrEmpty(companyID))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(extrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                var sql = $@"SELECT  table1.ExtrSource ,
        table1.CompanyID ,
        table1.YearV ,
        table1.Weekv ,
        table2.SourceYear ,
        table2.SourceWeek
FROM    ( SELECT    *
          FROM      ndw.ndw_CalendarDays cal
          WHERE     ExtrSource = '{extrSource}'
                    AND CompanyID = '{companyID}'
                    AND YearV >= YEAR(CURRENT_DATE)
                    AND Weekv >= WEEK(CURRENT_DATE)
                    AND YearV <= ( YEAR(CURRENT_DATE) + 1 )
        ) table1
        LEFT JOIN ( SELECT  *
                    FROM    ndw.ndw_details_percentage_setting
                    WHERE   ExtrSource = '{extrSource}'
                            AND CompanyID = '{companyID}'
                  ) table2 ON table1.ExtrSource = table2.ExtrSource
                              AND table1.CompanyID = table2.CompanyID
                              AND table1.YearV = table2.Year
                              AND table1.Weekv = table2.Week

GROUP BY  table1.ExtrSource ,
          table1.CompanyID ,
          table1.YearV ,
          table1.Weekv ,
          table2.SourceYear ,
          table2.SourceWeek
ORDER BY table1.YearV ,
        table1.Weekv";
                var cmd = Helper.GetSqlStringCommand(sql);
                var dt = Helper.ExecuteDataTable(cmd);
                var group = ModelConvertHelper<DwDetailsPercentageSettingModel.TitleModel>.ConvertToModel(dt)
                    .GroupBy(d => d.YearV).ToList();
                return Success(group);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error("获取数据失败!");
            }
        }

        /// Writer：ljj
        /// Create Date：2018-01-04
        [MustLogin]
        [JsonType]
        [Description("复制周占比")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult WeekCopy([ParamDescription("关键字")] DwDetailsPercentageSettingModel.CopyModel param)
        {
            try
            {
                const string sql = @"DELETE  FROM ndw.ndw_details_percentage_setting WHERE   Extrsource = '{6}' AND CompanyId = '{7}' AND Year = {0} AND Week = {1};
INSERT  INTO ndw.ndw_details_percentage_setting ( CompanyId , Extrsource , Year , Week , Category , Gender , Detail , Persentage , CreateTime , UpdateTime , Operator , IsHome , SourceYear , SourceWeek )
        SELECT  Extrsource , CompanyId , {0} , {1} , Category , Gender , Detail , Persentage , '{2}' , '{2}' , '{3}' , IsHome , {4} , {5}
        FROM    ndw.ndw_details_percentage_setting WHERE   Extrsource = '{6}' AND CompanyId = '{7}' AND Year = {4} AND Week = {5};";
                if (param == null) return Error("参数对象为空");
                if (param.list == null) return Error("参数对象为空!");
                var companyID = UserInfo.UserCompanyId;
                var extrSource = UserInfo.UserExtrSource;
                if (string.IsNullOrEmpty(companyID))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(extrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                var sb = new StringBuilder();
                foreach (var t in param.list)
                {
                    sb.AppendLine(string.Format(sql, t.TargeYear, t.TargeWeek, DateTime.Now,
                        UserInfo.UserID, param.SourceYear, param.SourceWeek, extrSource, companyID));
                }
                var cmd = Helper.GetSqlStringCommand(sb.ToString());
                Helper.ExecuteNonQuery(cmd);
                return Success(0);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error("复制失败!");
            }
        }

        /// Writer：ljj
        /// Create Date：2018-01-04
        [MustLogin]
        [JsonType]
        [Description("小类_细项设置")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult ModifyDwDetailsPercentageSetting([ParamDescription("关键字")] DwDetailsPercentageSettingModel.ModifyListModel param)
        {
            try
            {
                if (param == null) return Error("参数对象为空");
                if (param.modifyList == null) return Error("参数对象为空!");
                var companyID = UserInfo.UserCompanyId;
                var extrSource = UserInfo.UserExtrSource;
                if (string.IsNullOrEmpty(companyID))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(extrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                var list = new List<DwDetailsPercentageSettingModel.CreateModel>();
                foreach (var item in param.modifyList)
                {
                    list.AddRange(item.list.Select(d => new DwDetailsPercentageSettingModel.CreateModel
                    {
                        CompanyID = companyID,
                        ExtrSource = extrSource,
                        Year = item.Year,
                        Week = item.Week,
                        Category = item.Category,
                        Gender = item.Gender,
                        Detail = d.Detail,
                        IsHome = d.IsHome,
                        Persentage = d.Persentage,
                        Operator = UserInfo.UserID,
                        UpdateTime = DateTime.Now,
                    }));
                }
                var dt = DataTableHelper.LinqToDataTable(list);
                MergeDwDetailsPercentageSetting(dt);
                return Success(0);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error("保存失败!");
            }
        }

        /// <summary>
        /// Merge
        /// </summary>
        /// <param name="dt"></param>
        /// Writer：ljj
        /// Create Date：2018-01-04
        public void MergeDwDetailsPercentageSetting(DataTable dt)
        {
            try
            {
                var tempTableName = $"ndw.temp_{Guid.NewGuid():N}";
                const string onConditions = @"targetTable.CompanyID=sourceTable.CompanyID
    and targetTable.ExtrSource=sourceTable.ExtrSource
	and targetTable.Year=sourceTable.Year
	and targetTable.Week=sourceTable.Week
	and targetTable.Category=sourceTable.Category
	and targetTable.Gender=sourceTable.Gender
	and targetTable.Detail=sourceTable.Detail
	and targetTable.IsHome=sourceTable.IsHome";
                var setConditions = $@"Persentage=sourceTable.Persentage ,
    UpdateTime=sourceTable.UpdateTime ,
    Operator=sourceTable.Operator";
                const string insertConditions = @"";
                const string valuesConditions = @"";
                Helper.Merge(tempTableName, "ndw.ndw_details_percentage_setting", dt, onConditions, setConditions,
                    insertConditions, valuesConditions, false);
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

//        /// Writer：ljj
//        /// Create Date：2018-01-04
//        [MustLogin]
//        [Description("批量设置标准SKC数")]
//        [ReturnType(typeof(int), "0-成功")]
//        public ApiResult BatchDwDetailsPercentageSetting([ParamDescription("标准SKC数")] long StandardSKC,
//            [ParamDescription("年份")] string Year, [ParamDescription("周")] string Week = "",
//            [ParamDescription("大类")] string Category = "", [ParamDescription("性别")] string Gender = "",
//            [ParamDescription("详细")] string Detail = "")
//        {
//            try
//            {
//                var companyID = UserInfo.UserCompanyId;
//                var extrSource = UserInfo.UserExtrSource;
//                if (string.IsNullOrEmpty(companyID))
//                {
//                    return Error("该用户不属于任何公司!");
//                }
//                if (string.IsNullOrEmpty(extrSource))
//                {
//                    return Error("该用户所在公司没有任何数据源!");
//                }
//                var categoryStr = Category.GetString();
//                var detailStr = Detail.GetString();
//                var sql = $@"UPDATE ndw.ndw_details_percentage_setting
//SET StandardSKC = {StandardSKC}, UpdateTime = '{DateTime.Now}', Operator = '{UserInfo.UserID}'
//WHERE CompanyId = '{companyID}' AND Extrsource = '{extrSource}' AND Year = {Year} 
//{(string.IsNullOrEmpty(Week) ? "" : $"AND Week = {Week}")}
//{(string.IsNullOrEmpty(Category) ? "" : $"AND Category in {categoryStr}")}
//{(string.IsNullOrEmpty(Gender) ? "" : $"AND Gender = '{Gender}'")}
//{(string.IsNullOrEmpty(Detail) ? "" : $"AND Detail in {detailStr}")};";
//                var cmd = Helper.GetSqlStringCommand(sql);
//                Helper.ExecuteNonQuery(cmd);
//                return Success(0);
//            }
//            catch (Exception ex)
//            {
//                Log.Error(ex);
//                return Error(ex);
//            }
//        }

        /// Writer：ljj
        /// Create Date：2018-01-05
        [MustLogin]
        [Description("获取历史销售占比")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult CreateHistory()
        {
            //var tempTableName = $@"ndw.temp_{Guid.NewGuid():N}";
            try
            {
                var companyID = UserInfo.UserCompanyId;
                var extrSource = UserInfo.UserExtrSource;
                if (string.IsNullOrEmpty(companyID))
                {
                    return Error("该用户不属于任何公司!");
                }
                if (string.IsNullOrEmpty(extrSource))
                {
                    return Error("该用户所在公司没有任何数据源!");
                }
                var sql = $@"DELETE  FROM ndw.ndw_details_percentage_setting
WHERE   Week = 0;
INSERT  INTO ndw.ndw_details_percentage_setting
        ( CompanyId ,
          Extrsource ,
          Year ,
          Week ,
          Category ,
          Gender ,
          Detail ,
          Persentage ,
          CreateTime ,
          UpdateTime ,
          Operator ,
          IsHome
        )
        SELECT  item.CompanyID ,
                item.ExtrSource ,
                YEAR(CURRENT_DATE) ,
                0 ,
                item.KindID ,
                item.SexID ,
                item.ItemorSub ,
                per.Persentage ,
                '{DateTime.Now}' ,
                '{DateTime.Now}' ,
                '{UserInfo.UserID}' ,
                item.IsHome
        FROM    ( SELECT    *
                  FROM      ndw.ndw_KindToItem
                  WHERE     CompanyID = '{companyID}'
                            AND ExtrSource = '{extrSource}'
                ) item
                LEFT JOIN ( SELECT  *
                            FROM    public.vw_details_percentage
                            WHERE   CompanyID = '{companyID}'
                          ) per ON item.CompanyID = per.CompanyID
                                   AND item.KindID = per.KindID
                                   AND item.SexID = per.SexID
                                   AND item.IsHome = per.IsHome
                                   AND item.ItemorSub = per.ItemOrSub";
                //                var sql = $@"DROP TABLE IF EXISTS {tempTableName};

                //SELECT  item.CompanyID ,
                //        item.ExtrSource ,
                //        0 AS Year ,
                //        0 AS Week ,
                //        item.KindID AS Category ,
                //        item.SexID AS Gender ,
                //        item.ItemorSub AS Detail ,
                //        per.Persentage ,
                //        item.IsHome
                //INTO    {tempTableName}
                //FROM    ( SELECT    *
                //          FROM      ndw.ndw_KindToItem
                //          WHERE     CompanyID = '{companyID}'
                //                    AND ExtrSource = '{extrSource}'
                //        ) item
                //        LEFT JOIN ( SELECT  *
                //                    FROM    public.vw_details_percentage
                //                    WHERE   CompanyID = '{companyID}'
                //                  ) per ON item.CompanyID = per.CompanyID
                //                           AND item.KindID = per.KindID
                //                           AND item.SexID = per.SexID
                //                           AND item.IsHome = per.IsHome
                //                           AND item.ItemorSub = per.ItemOrSub;

                //MERGE INTO ndw.ndw_details_percentage_setting targetTable
                //    USING {tempTableName} sourceTable
                //    ON ( targetTable.CompanyID = sourceTable.CompanyID
                //         AND targetTable.ExtrSource = sourceTable.ExtrSource
                //         AND targetTable.Year = sourceTable.Year
                //         AND targetTable.Week = sourceTable.Week
                //         AND targetTable.Category = sourceTable.Category
                //         AND targetTable.Gender = sourceTable.Gender
                //         AND targetTable.Detail = sourceTable.Detail
                //         AND targetTable.IsHome = sourceTable.IsHome
                //       )
                //    WHEN MATCHED 
                //        THEN UPDATE
                //          SET       Persentage = sourceTable.Persentage ,
                //                    UpdateTime = '{DateTime.Now}'
                //    WHEN NOT MATCHED 
                //        THEN INSERT (
                //                      CompanyId ,
                //                      Extrsource ,
                //                      Year ,
                //                      Week ,
                //                      Category ,
                //                      Gender ,
                //                      Detail ,
                //                      Persentage ,
                //                      StandardSKC ,
                //                      CreateTime ,
                //                      UpdateTime ,
                //                      Operator ,
                //                      IsHome
                //                    )
                //          VALUES    ( sourceTable.CompanyId ,
                //                      sourceTable.Extrsource ,
                //                      sourceTable.Year ,
                //                      sourceTable.Week ,
                //                      sourceTable.Category ,
                //                      sourceTable.Gender ,
                //                      sourceTable.Detail ,
                //                      sourceTable.Persentage ,
                //                      sourceTable.StandardSKC ,
                //                      '{DateTime.Now}' ,
                //                      '{DateTime.Now}' ,
                //                      '{UserInfo.UserID}' ,
                //                      sourceTable.IsHome 
                //                    );";
                var cmd = Helper.GetSqlStringCommand(sql);
                Helper.ExecuteNonQuery(cmd);
                return Success(0);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return Error("获取历史销售占比失败!");
            }
            //finally
            //{
            //    Helper.DropTempTable(tempTableName);
            //}
        }
    }
}
